using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.CompositeWeb.Interfaces;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.CompositeWeb;
using CompositeWeb.Extensions.Configuration;
using CompositeWeb.Extensions.Interfaces;
using Microsoft.Practices.CompositeWeb.Configuration;
using System.Configuration;

namespace CompositeWeb.Extensions.Services
{
    /// <summary>
    /// Implements a <see cref="IModuleEnumerator"/> that gets the module metadata from
    /// the module configuration files.
    /// </summary>
    public class WebModuleEnumerator : IModuleEnumerator
    {
        private IModuleInfo[] _modules;
        private ICustomModuleInfoStore _store;

        /// <summary>
        /// Initializes a new instance of <see cref="WebModuleEnumerator"/>.
        /// </summary>
        /// <param name="store">The <see cref="IModuleInfoStore"/> to use to get the module configuration.</param>
        [InjectionConstructor]
        public WebModuleEnumerator([ServiceDependency] ICustomModuleInfoStore store)
        {
            _store = store;
        }

        /// <summary>
        /// Gets the list of modules needed by the application.
        /// </summary>
        /// <returns>An array of <see cref="IModuleInfo"/>.</returns>
        public IModuleInfo[] EnumerateModules()
        {
            if (_modules != null) return _modules;

            List<CustomDependantModuleInfo> moduleInfos = new List<CustomDependantModuleInfo>();
            CustomModulesConfigurationSection section = _store.GetModuleConfigurationSection();
            ValidateDuplicates(section);

            foreach (CustomModuleConfigurationElement data in section.Modules)
            {
                CustomDependantModuleInfo moduleInfo = new CustomDependantModuleInfo(data.Name, data.AssemblyName, data.VirtualPath);
                if (data.Dependencies.Count > 0)
                {
                    moduleInfo.Dependencies = new ModuleDependency[data.Dependencies.Count];
                    for (int i = 0; i < data.Dependencies.Count; i++)
                    {
                        moduleInfo.Dependencies[i] = new ModuleDependency();
                        moduleInfo.Dependencies[i].Name = data.Dependencies[i].Module;
                    }
                }

                if (data.Services.Count > 0)
                {
                    moduleInfo.Services = new ServiceInfo[data.Services.Count];

                    for (int i = 0; i < data.Services.Count; i++)
                    {
                        moduleInfo.Services[i] = new ServiceInfo(data.Services[i].RegisterAs, data.Services[i].Type, data.Services[i].Scope);
                    }
                }

                moduleInfos.Add(moduleInfo);
            }

            if (moduleInfos.Count > 0)
            {
                _modules = SortModules(moduleInfos);
            }
            else
            {
                _modules = moduleInfos.ToArray();
            }
            return _modules;
        }

        private static void ValidateDuplicates(CustomModulesConfigurationSection section)
        {
            foreach (CustomModuleConfigurationElement data in section.Modules)
            {
                List<CustomModuleConfigurationElement> found = section.Modules.FindAll(delegate(CustomModuleConfigurationElement match)
                {
                    return !string.IsNullOrEmpty(match.VirtualPath) &&
                        (String.Equals(match.VirtualPath, data.VirtualPath, StringComparison.InvariantCultureIgnoreCase)
                        || String.Equals(match.AssemblyName, data.AssemblyName, StringComparison.InvariantCultureIgnoreCase));
                });
                if (found.Count > 1)
                    ThrowConfigurationErrorsException(data, found);
            }
        }

        private static void ThrowConfigurationErrorsException(CustomModuleConfigurationElement data, List<CustomModuleConfigurationElement> found)
        {
            string moduleNames = String.Empty;
            foreach (CustomModuleConfigurationElement duplicatedModule in found)
            {
                if (moduleNames.Length > 0)
                    moduleNames += ", ";

                moduleNames += data.Name;
            }
            throw new ConfigurationErrorsException(String.Format(Properties.Resources.DuplicatedModuleLocationOrAssemblyName, moduleNames));
        }

        private static IModuleInfo[] SortModules(List<CustomDependantModuleInfo> modules)
        {
            List<CustomDependantModuleInfo> result = new List<CustomDependantModuleInfo>();
            Dictionary<string, CustomDependantModuleInfo> index = new Dictionary<string, CustomDependantModuleInfo>();
            ModuleDependencySolver solver = new ModuleDependencySolver();
            foreach (CustomDependantModuleInfo moduleInfo in modules)
            {
                index.Add(moduleInfo.Name, moduleInfo);
                solver.AddModule(moduleInfo.Name);
                if (moduleInfo.Dependencies != null)
                {
                    foreach (ModuleDependency dependency in moduleInfo.Dependencies)
                    {
                        solver.AddDependency(moduleInfo.Name, dependency.Name);
                    }
                }
            }
            string[] sortedIndex = solver.Solve();
            for (int i = 0; i < sortedIndex.Length; i++)
            {
                string moduleName = sortedIndex[i];
                result.Add(index[moduleName]);
            }
            return result.ToArray();
        }
    }
}
